package com.tianpengtech.common.util;

import com.google.gson.Gson;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;

import java.io.InputStream;
import java.util.UUID;

/**
 * Created by GGD on 2017/5/31 0031.
 */
public class QiNiuUtil {
    //构造一个带指定Zone对象的配置类
    private static Configuration cfg = new Configuration(Zone.zone0());
    //...其他参数参考类注释
    private static UploadManager uploadManager = new UploadManager(cfg);
    //...生成上传凭证，然后准备上传
    private static Prop prop = new Prop("qiniu.properties");
    private static String accessKey = prop.get("qiniu.accesskey");
    private static String secretKey = prop.get("qiniu.secretkey");
    private static String bucket = prop.get("qiniu.bucket");
    public static String DOMAIN = prop.get("qiniu.domain");


    public static String getToken(){
        Auth auth = Auth.create(accessKey, secretKey);
//        String upToken = auth.uploadToken(bucket);
        StringMap stringMap = new StringMap();
        stringMap.put("mimeLimit","image/*");
        String upToken=auth.uploadToken(bucket,null,3600,stringMap);
        return upToken;
    }

    public static String upload(InputStream path,String category) throws QiniuException {
        Auth auth = Auth.create(accessKey, secretKey);
        
        String upToken = auth.uploadToken(bucket,null, 3600, new StringMap()
                .putNotEmpty("saveKey",category+UUID.randomUUID().toString()), true);
        try {
            Response response = uploadManager.put(path,null,upToken,null, null);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            return DOMAIN+"/"+putRet.key;
        } catch (QiniuException ex) {
            throw ex;
        }
    }

    public static void deleteQiNiuFile(String fileKey) throws QiniuException{
		Configuration cfg = new Configuration(Zone.autoZone());
		Auth auth = Auth.create(accessKey, secretKey);
		BucketManager bucketManager = new BucketManager(auth, cfg);
		bucketManager.delete(bucket, fileKey);
	}

    public static void main(String[] args) {

    }


}
